import { Emitter } from 'mitt';
import { onBeforeUpdate, ref, inject, toRaw, isReactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import mqtt from '/@/api/smoke/mqtt';
import { ElMessage } from 'element-plus';
import { Local, Session } from '/@/utils/storage';
import { getUrl } from '/@/utils/hm';
import { smokeStore } from '/@/stores/smoke';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import router from '../router';

export function useSmoke() {
	// 拼接设备地址
	const getAddress = (rowItem: any) => {
		let row = isReactive(rowItem) ? toRaw(rowItem) : rowItem;
		let address = `${row.communityName}
    ${row.buildNum ? row.buildNum + ' 栋' : ' '}
    ${row.utilNum ? row.utilNum + ' 单元' : ''}
    ${row.floorNum ? row.floorNum + ' 楼' : ''}
		${row.deviceAddr ? `（ ${row.deviceAddr.trim()} ）` : ''}
    `;
		return address;
	};

	

	const getFileUrl = (url: string) => {
		let baseUrl = getUrl('baseURL');
		if (url.includes('http')) {
			return url;
		} else {
			return `${baseUrl}${url}`;
		}
	};

	// 计算设备是否离线
	const isOffline = (timeStr: string) => {
		if (timeStr) {
			let cTime: number = Number(new Date(timeStr).getTime());
			let current: number = Number(Date.now());
			return (current - cTime) / 1000 >= 30;
		} else {
			return true;
		}
	};

	// 角色计算
	const getRole = () => {
		const stores = useUserInfo();
		const { userInfos, roleIds, communitys } = storeToRefs(stores);
		const deptId = userInfos.value.deptId;

		if (roleIds.value.length == 0 || !deptId) {
			router.push('/login');
		}

		return { roleIds, deptId, communitys };
	};

	return { getAddress, getFileUrl, isOffline, getRole };
}
